import datetime
import os
import sys

args = sys.argv
if len(args) > 1:
    zero_str = args[1] + ' 00:00:00'
    last_str = args[2] + ' 23:59:59'
    today_str = args[1] + '-' + args[2]
else:
    now = datetime.datetime.now()
    prev = now - datetime.timedelta(days=3)
    zero = prev - datetime.timedelta(hours=prev.hour, minutes=prev.minute, seconds=prev.second,
                                     microseconds=prev.microsecond)
    last = zero + datetime.timedelta(hours=23, minutes=59, seconds=59)
    zero_str = datetime.datetime.strftime(zero, "%Y-%m-%d %H:%M:%S")
    last_str = datetime.datetime.strftime(last, "%Y-%m-%d %H:%M:%S")
    today_str = datetime.datetime.strftime(zero, "%Y-%m-%d")

sql = "select * from cg_sj_sjj_sj02_predict where GMT_CREATE > '{}' and GMT_CREATE < '{}'".format(zero_str, last_str)
delete_sql = "delete from cg_sj_sjj_sj02_predict where GMT_CREATE > '{}' and GMT_CREATE < '{}'".format(zero_str,
                                                                                                             last_str)
print(delete_sql)

user = 'root'
host = '127.0.0.1'
password = 'Cisco#123'
db = 'ironman_prod'
port = '13306'
file_path = '/var/hblg/dump/' + today_str + '.txt'
csv_path = '/var/hblg/dump/' + today_str + '.csv'

exec_cmd = "echo \"" + sql + "\" | mysql -u {} -h {} -p{} -P {} --default-character-set=utf8  -B -D{} > {}".format(
    user, host, password, port, db, file_path
)

os.system(exec_cmd)
os.system("cat {} | tr '\t' ',' > {}".format(file_path, csv_path))
os.system("gzip {}".format(csv_path))
print("remove " + file_path)
os.system("rm -rf {}".format(file_path))

delete_cmd = "echo \"" + delete_sql + "\" | mysql -u {} -h {} -p{} -P {} --default-character-set=utf8  -B -D{}".format(
    user, host, password, port, db)
# os.system(exec_cmd)
